package my.webservices.model.util;

import java.io.PrintWriter;

import my.webservices.beans.Vehicle;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hsqldb.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataSetup implements DataSetupMBean {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private Server server;

	private SessionFactory sessionFactory;

	/**
	 * @see my.webservices.model.util.DataSetupMBean#startServer()
	 */
	public void startServer() {
		server = new Server();
		server.setAddress("localhost");
		server.setDatabaseName(0, "vehicleHistory");
		server.setDatabasePath(0, "file:target/data");
		server.setPort(9234);
		server.setTrace(true);
		server.setLogWriter(new PrintWriter(System.out));
		server.start();
	}

	/**
	 * @see my.webservices.model.util.DataSetupMBean#insertDummyData()
	 */
	public void insertDummyData() {
		logger.trace("Inside init");
		if (server != null) {
			server.checkRunning(true);
		}
		Vehicle veh = new Vehicle();
		veh.setVin("123456");
		veh.setVehicleNumber("DL 03 CU 3818");
		veh.setMake(2010);
		veh.setModel("BMW M3 Coupe");
		logger.debug("Before saving, veHist {}", veh);
		logger.debug("SessionFactory {}", getSessionFactory());
		logger.debug("Session {}", getSessionFactory().openSession());
		Session session = getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.save(veh);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public SessionFactory getSessionFactory() {
		if (sessionFactory == null) {
			try {
				sessionFactory = new AnnotationConfiguration().configure()
						.buildSessionFactory();
			} catch (Throwable ex) {
				System.err.println("Initial SessionFactory creation failed."
						+ ex);
				throw new ExceptionInInitializerError(ex);
			}
		}
		return sessionFactory;
	}

	/**
	 * @see my.webservices.model.util.DataSetupMBean#stopServer()
	 */
	public void stopServer() {
		server.shutdown();

	}

}
